/**
 * @author amalafe
 */
Namespace("sketch.framework");

(function($){
	var fwk = sketch.framework;		
		
	fwk.ImageElement = klass(fwk.UIElement, {
        _constructor:function(){
            var that = this;

			this.properties.type = 'ImageElement';
            this._src = this.properties.createProperty("src", "Source", null)
                .editorTemplate("#editor-imagepicker");

            this._src.changedEvent.bind(function(event){
                that._createImageBuffer(event.newValue);
            });
	    },
        _createImageBuffer: function(src){
            var that = this;
            var source;

            if (src === null){
                if (this._showEmptyImage){
                    source = this._emptyImageSrc ? this._emptyImageSrc : "/img/ui/no-image.png";
                }
                else{
                    return;
                }
            }
            else{
                source = src;
            }

            var image = new Image();

            image.onload = function(){
                that._buffer = new fwk.DrawBuffer();
                that._buffer.width(image.width);
                that._buffer.height(image.height);
                that._buffer.context.drawImage(image, 0, 0);

                that.width(image.width);
                that.height(image.height);

                that.onresize(that.getBoundaryRect());
            };
            image.src = source;
        },
        src: function(value){
            if (arguments.length === 1){
                this._src(value);
                this._createImageBuffer(value);
            }
            return this._src();
        },
		debugInfo : function(){
		    return 'Debug:(' +this.left() + ',' + this.top() + ',' + this.width() + ',' + this.height() +  ')';
	    },	
        drawSelf : function(context){
            context.rectPath(this.left(), this.top(), this.width(), this.height());
            context.clip();
            if (this._buffer){
                this._buffer.draw(context, this.left(), this.top());
            }
        },
        getType:function(){
            return "ImageElement";
        },
        showEmptyImage: function(emptyImageSrc){
            this._showEmptyImage = true;
            this._emptyImageSrc = emptyImageSrc;
        }
    });

    fwk.ImageElement.create = function(src){
        var image = new fwk.ImageElement();
        image.src(src);
        return image;
    };

})(jQuery);
